package com.clps.rulesregulations.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.clps.rulesregulations.dao.RegulationDao;
import com.clps.rulesregulations.domain.*;
import com.clps.rulesregulations.service.RegulationService;
import com.clps.rulesregulations.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 首页逻辑处理
 *
 * @author zhangchao
 * @date 2018-10-09
 */
@Service("regulationService")
public class RegulationServiceImpl implements RegulationService {
    @Autowired
    private RegulationDao regulationDao;

    @Override
    public List<ResourceTree> findAllAsTree() {
        LinkedList<ResourceTree> resourceTrees = regulationDao.findAllAsTree();
        ResourceTree root = new ResourceTree(0, null);
        root = TreeUtil.getTree(root, resourceTrees);
        return TreeUtil.createDepthFirstTraversalList(root);
    }

    @Override
    public List<ResourceTree> findAllAsTreeByParentId(String id, String parentId) {
        LinkedList<ResourceTree> resourceTrees = regulationDao.findAllAsTreeByParentId(id);
        ResourceTree root = new ResourceTree(Integer.valueOf(parentId), "name");
        root = TreeUtil.getTree(root, resourceTrees);
        return TreeUtil.createDepthFirstTraversalList(root);
    }

    @Override
    public List<ResourceTree> findMenuTree() {
        LinkedList<ResourceTree> resourceTrees = regulationDao.findMenuTree();
        ResourceTree root = new ResourceTree(0, null);
        root = TreeUtil.getTree(root, resourceTrees);
        return TreeUtil.createDepthFirstTraversalList(root);
    }

    @Override
    public List<ResourceTree> findDeptTrees() {


//        LinkedList<ResourceTree> resourceTrees = regulationDao.findDeptTrees();
        List<Department> keywordList = regulationDao.findKeyword();
        LinkedList<ResourceTree> allLinkedList = new LinkedList<ResourceTree>();
        if (keywordList != null && keywordList.size() > 0) {

            for (int i = 0; i < keywordList.size(); i++) {
                Department dp = keywordList.get(i);
                String keyword = dp.getKeyword();
                String[] arr = keyword.split(",");

                for (int j = 0; j < arr.length; j++) {
                    LinkedList<ResourceTree> linkedList = regulationDao.selectByKeyword(arr[j], dp.getId());
                    allLinkedList.addAll(linkedList);
                }
            }
            Iterator aiterator = allLinkedList.iterator();
            while (aiterator.hasNext()) {
                ResourceTree rt = (ResourceTree) aiterator.next();
                rt.setOldId(rt.getId());
                rt.setId(Integer.valueOf(rt.getId() + "0" + rt.getTopId()));
                rt.setParentId(Integer.valueOf(rt.getParentId() + "0" + rt.getTopId()));
            }

            LinkedList<ResourceTree> deptlist = regulationDao.findAllDept();
            Iterator deptiter = deptlist.iterator();
            while (deptiter.hasNext()) {
                ResourceTree rt = (ResourceTree) deptiter.next();
                rt.setOldId(rt.getId());
            }
            allLinkedList.addAll(deptlist);
        }

        Map map = new HashMap();
        Iterator aiterator = allLinkedList.iterator();
        while (aiterator.hasNext()) {
            ResourceTree rt = (ResourceTree) aiterator.next();
            Integer topId = rt.getTopId();
            if (topId != 0) {
                map.put(rt.getId(), rt.getId());
            }
        }

        aiterator = allLinkedList.iterator();
        while (aiterator.hasNext()) {
            ResourceTree rt = (ResourceTree) aiterator.next();
            Integer topId = rt.getTopId();
            if (topId != 0) {
                Integer parentId = rt.getParentId();
                if (map.get(parentId) == null) {
                    rt.setParentId(rt.getTopId());
                }
            }
        }

        ResourceTree root = new ResourceTree(0, null);
        root = TreeUtil.getTree(root, allLinkedList);
        return TreeUtil.createDepthFirstTraversalList(root);
    }

    @Override
    public List<Integer> findAllRegulationIds() {
        return regulationDao.findAllRegulationIds();
    }

    @Override
    public List<Department> selectDepartmentKey() {
        return regulationDao.selectDepartmentKey();
    }

    @Override
    public List<ResourceTree> findDirAsTree() {
        LinkedList<ResourceTree> resourceTrees = regulationDao.findDirAsTree();
        ResourceTree root = new ResourceTree(0, null);
        root = TreeUtil.getTree(root, resourceTrees);
        return TreeUtil.createDepthFirstTraversalList(root);
    }

    @Override
    public List<ResourceTree> findAllDirAsTree() {
        LinkedList<ResourceTree> resourceTrees = regulationDao.findAllDirAsTree();
        ResourceTree root = new ResourceTree(0, null);
        root = TreeUtil.getTree(root, resourceTrees);
        return TreeUtil.createDepthFirstTraversalList(root);
    }

    @Override
    public List<Integer> findDirRegulationIds() {
        return regulationDao.findDirRegulationIds();
    }

    @Override
    public List<Integer> findAllDirRegulationIds() {
        return regulationDao.findAllDirRegulationIds();
    }

    @Override
    public void addRegulations(Regulation regulation) {
        regulationDao.addRegulations(regulation);
    }

    @Override
    public void updateRegulationsList(List list) {
        regulationDao.updateRegulationsList(list);
    }

    @Override
    public void deleteRegulationsList(List list) {
        regulationDao.deleteRegulationsList(list);
    }

    @Override
    public void deleteRuleList(List list) {
        regulationDao.deleteRuleList(list);
    }

    @Override
    public Integer getMaxSorder(Integer parentId) {
        return regulationDao.getMaxSorder(parentId);
    }

    @Override
    public void saveRule(Rule rule) {
        regulationDao.saveRule(rule);
    }

    @Override
    public void saveRuleHis(Rule rule) {
        regulationDao.saveRuleHis(rule);
    }

    @Override
    public Rule selectRule(String id) {
        return regulationDao.selectRule(id);
    }

    @Override
    public Rule selectRuleByMenuId(String id) {
        return regulationDao.selectRuleByMenuId(id);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    @Override
    public void fileclickcount(String id) {
        Rule rule = regulationDao.selectRuleByMenuId(String.valueOf(id));

        String ruleId = String.valueOf(rule.getId());
        HotSearch hs = regulationDao.getFileHotSearchCount(ruleId);

        if (hs == null) {
            regulationDao.insertFileHotSearchCount(ruleId);

        } else {
            regulationDao.updateFileHotSearchCount(ruleId);

        }


    }

    @Override
    public Rule selectRuleHis(String id) {
        return regulationDao.selectRuleHis(id);
    }

    @Override
    public void deleteRuleHis(String id) {
        regulationDao.deleteRuleHis(id);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    @Override
    public boolean updateRule(Rule rule) {

        Rule rm = selectRule(String.valueOf(rule.getId()));
        List<Regulation> regulationList = selectAllSonFiles(String.valueOf(rm.getParentId()), String.valueOf(rm.getCatalogId()));
        if (regulationList != null && regulationList.size() > 0) {
            for (int i = 0; i < regulationList.size(); i++) {
                Regulation rs = regulationList.get(i);
                String sonTitle = rs.getName();
                if (rule.getTitle().equals(sonTitle)) {
                    return false;
                }
            }
        }

        Rule saveRule = new Rule();
        //插入新的到历史表，用来查看版本
        saveRule.setId(rule.getId());
        saveRule.setCreateTime(new Date());
        saveRule.setTitle(rule.getTitle());
        saveRule.setContent(rule.getContent());
        Session session = SecurityUtils.getSubject().getSession();
        User u = (User) session.getAttribute("userSession");
        saveRule.setOperator(u.getUsername());
        regulationDao.saveRuleHis(saveRule);

        Rule updateRule = new Rule();
        updateRule.setId(rule.getId());
        updateRule.setTitle(rule.getTitle());
        updateRule.setContent(rule.getContent());
        updateRule.setUpdateTime(new Date());
        regulationDao.updateRule(updateRule);


        rule.setCatalogId(rm.getCatalogId());
        updateRegulationMenu(rule);

        //未測試
        Map<String, Object> esmap = new HashMap<String, Object>();
        esmap.put("title", rule.getTitle());
        esmap.put("content", DelTagsUtil.delHtmlTags(Base64Util.decode(rule.getContent())));
        esmap.put("wordid", rule.getId());

        try {
            ElasticsearchUtils.updateDataById(JSONObject.parseObject(JSONObject.toJSONString(esmap)), "rules_and_regulations", "rule", "id=" + rule.getId());

        } catch (Exception e) {

        }
        return true;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    @Override
    public boolean coverfile(Rule rule) {

        Rule rm = selectRule(String.valueOf(rule.getId()));

        Rule saveRule = new Rule();
        //插入新的到历史表，用来查看版本
        saveRule.setId(rule.getId());
        saveRule.setCreateTime(new Date());
        saveRule.setTitle(rule.getTitle());
        saveRule.setContent(rule.getContent());
        Session session = SecurityUtils.getSubject().getSession();
        User u = (User) session.getAttribute("userSession");
        saveRule.setOperator(u.getUsername());
        regulationDao.saveRuleHis(saveRule);

        Rule updateRule = new Rule();
        updateRule.setId(rule.getId());
        updateRule.setTitle(rule.getTitle());
        updateRule.setContent(rule.getContent());
        updateRule.setUpdateTime(new Date());
        regulationDao.updateRule(updateRule);

        rule.setCatalogId(rm.getCatalogId());
        updateRegulationMenu(rule);

        //未測試
        Map<String, Object> esmap = new HashMap<String, Object>();
        esmap.put("title", rule.getTitle());
        esmap.put("content", DelTagsUtil.delHtmlTags(Base64Util.decode(rule.getContent())));
        esmap.put("wordid", rule.getId());

        try {
            ElasticsearchUtils.updateDataById(JSONObject.parseObject(JSONObject.toJSONString(esmap)), "rules_and_regulations", "rule", "id=" + rule.getId());

        } catch (Exception e) {

        }
        return true;
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    @Override
    public void deleteRule(Rule rule) {
        Long id = rule.getId();
        //先查后删
        Rule rm = regulationDao.selectRule(String.valueOf(id));
//        rule.setCatalogId(rm.getCatalogId());
        regulationDao.deleteRegulationMenuByid(rm.getCatalogId());
        regulationDao.deleteRule(id);

        try {
            ElasticsearchUtils.deleteDataById("rules_and_regulations", "rule", "id=" + rule.getId());
        } catch (Exception e) {

        }

    }

    @Override
    public void updateRegulationMenu(Rule rule) {
        regulationDao.updateRegulationMenu(rule);
    }

    @Override
    public HotSearch getFileHotSearchCount(String id) {
        return regulationDao.getFileHotSearchCount(id);
    }

    @Override
    public void insertFileHotSearchCount(String id) {
        regulationDao.insertFileHotSearchCount(id);
    }

    @Override
    public void updateFileHotSearchCount(String id) {
        regulationDao.updateFileHotSearchCount(id);
    }

    @Override
    public void insertAccessTalbe(AccessFile af) {
        regulationDao.insertAccessTalbe(af);
    }

    @Override
    public void revertRule(String id) {

        Rule rule = selectRuleHis(id);
        Rule hisRule = selectRuleHis(String.valueOf(rule.getRuleId()));

        Session session = SecurityUtils.getSubject().getSession();
        User u = (User) session.getAttribute("userSession");
        hisRule.setOperator(u.getUsername());
        hisRule.setCreateTime(new Date());
        saveRuleHis(hisRule);

        rule.setId(rule.getRuleId());

        Rule updateRule = new Rule();
        updateRule.setId(rule.getId());
        updateRule.setTitle(rule.getTitle());
        updateRule.setContent(rule.getContent());
        updateRule.setUpdateTime(new Date());
        regulationDao.updateRule(updateRule);
    }

    @Override
    public PageInfo<Rule> findAllRules(Map<String, Object> condition) {
        Integer pageNum = 1;
        try {
            pageNum = (Integer) condition.get("pageNum");
            pageNum = pageNum == 0 ? 1 : pageNum;
        } catch (Exception e) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, 10);
        List<Rule> rules = regulationDao.findAllRules(condition);
        return new PageInfo<>(rules);
    }

    @Override
    public PageInfo<Schedule> findAllSchedules(Map<String, Object> condition) {
        Integer pageNum = 1;
        try {
            pageNum = (Integer) condition.get("pageNum");
            pageNum = pageNum == 0 ? 1 : pageNum;
        } catch (Exception e) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, 9999);
        List<Schedule> rules = regulationDao.findAllSchedules(condition);
        return new PageInfo<>(rules);
    }

    @Override
    public PageInfo<Rule> findAllRulesHis(Map<String, Object> condition) {

        List<Rule> rules = regulationDao.findAllRulesHis(condition);
        return new PageInfo<>(rules);
    }

    @Override
    public PageInfo<Rule> listLatestUpdFile(Map<String, Object> condition) {
        List<Rule> rules = regulationDao.listLatestUpdFile(condition);
        return new PageInfo<>(rules);
    }

    @Override
    public PageInfo<Rule> showmoreeditfile(Map<String, Object> condition) {
        List<Rule> rules = regulationDao.showmoreeditfile(condition);
        return new PageInfo<>(rules);
    }

    @Override
    public PageInfo<Rule> showmorehotsearch(Map<String, Object> condition) {
        List<Rule> rules = regulationDao.showmorehotsearch(condition);
        return new PageInfo<>(rules);
    }

    @Override
    public PageInfo<Rule> listkeywordHot(Map<String, Object> condition) {
        List<Rule> rules = regulationDao.listkeywordHot(condition);
        return new PageInfo<>(rules);
    }

    @Override
    public Regulation selectNewParentInfo(Integer parentId) {
        return regulationDao.selectNewParentInfo(parentId);
    }

    @Override
    public List selectFileExistCount(List list) {
        return regulationDao.selectFileExistCount(list);
    }

    @Override
    public List<String> getDelDirList(Integer id) {
        return regulationDao.getDelDirList(id);
    }

    @Override
    public List selectFileDirExistCount(String id) {
        return regulationDao.selectFileDirExistCount(id);
    }

    @Override
    public Regulation selectRegByParentId(Integer parentId) {
        return regulationDao.selectRegByParentId(parentId);
    }

    @Override
    public List<Regulation> selectAllRegulations() {
        return regulationDao.selectAllRegulations();
    }

    @Override
    public void revertVersion(Rule rule) {
        regulationDao.revertVersion(rule);
    }

    @Override
    public void scheduleEdit(String _id, String schedule) {
        regulationDao.scheduleEdit(_id, schedule);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public void saveFileAndDir(List<Regulation> addList, List<Regulation> updateList, List<String> fileDirDelList, List<String> existFileList) {

        if (addList.size() > 0) {
            for (int i = 0; i < addList.size(); i++) {
                Regulation rl = addList.get(i);
                Regulation parentInfo = new Regulation();

                if ((String.valueOf(rl.getParentId()).length() == 6)) {
                    parentInfo = regulationDao.selectNewParentInfo(rl.getParentId());
                    rl.setParentId(parentInfo.getId());
                    rl.setUrl(parentInfo.getUrl() + Const.CONST_SEPERATE + rl.getLabel());

                } else {
                    parentInfo = regulationDao.selectRegByParentId(rl.getParentId());
                }
                String fullPath = parentInfo.getFullPath();

                if (!StringUtils.isEmpty(fullPath) && fullPath.endsWith(Const.CONST_SEPERATE)) {
                    rl.setFullPath(parentInfo.getFullPath() + rl.getParentId() + Const.CONST_SEPERATE);
                } else {
                    rl.setFullPath(parentInfo.getFullPath() + Const.CONST_SEPERATE + rl.getParentId() + Const.CONST_SEPERATE);
                }
//                int maxOrder = regulationDao.getMaxSorder(rl.getParentId());
                rl.setSorder(0);
                rl.setCreateTime(new Date());
                rl.setType(Const.DIR);
                rl.setIcon(Const.ICON_DIR);
                rl.setStatus(Integer.valueOf(Const.STATUS));
                rl.setCanDel(Integer.valueOf(Const.CANDEL));
                rl.setBatchOrder(99999);
                rl.setBatchNo(99999);
                regulationDao.addRegulations(rl);
            }

        }

        if (updateList.size() > 0) {
            regulationDao.updateRegulationsList(updateList);
        }

        if (fileDirDelList.size() > 0) {
            regulationDao.deleteRegulationsList(fileDirDelList);
        }

        if (existFileList != null && existFileList.size() > 0) {
            regulationDao.deleteRuleList(existFileList);

            for (int i = 0; i < existFileList.size(); i++) {
                String id = existFileList.get(i);
                try {
                    ElasticsearchUtils.deleteDataById("rules_and_regulations", "rule", "id=" + id);
                } catch (Exception e) {

                }

            }
        }
    }

    public static boolean is(String string, String mString) {
        if (StringUtils.isEmpty(mString)) {
            return false;
        }

        if (mString != null && mString.trim().length() != 0) {
            mString = mString.trim();

            for (int i = 0; i < mString.length(); ++i) {
                if (string.indexOf(mString.charAt(i)) == -1) {
                    return false;
                }
            }
        }

        return true;
    }

    public static boolean isNumeric(String mString) {
        return is("0123456789.", mString);
    }

    public static String getStr(String string, String mString) {
        StringBuffer strBuff = new StringBuffer();
        if (mString != null && mString.trim().length() != 0) {
            mString = mString.trim();

            for (int i = 0; i < mString.length(); ++i) {
                if (string.indexOf(mString.charAt(i)) == -1) {
                    return strBuff.toString();
                } else {
                    strBuff.append(mString.charAt(i));
                }
            }
        }
        return strBuff.toString();
    }

    public static String getParentId(String mString) {
        return getStr("0123456789.", mString);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public String detailDocxByStyle(Document doc, String catalogId, String upfileName) throws Exception {
        //记录文件tocid和文件内容对应关系
        Map fileMap = new HashMap();
        /** 处理目录信息start **/
        Elements links = doc.getElementsByTag("p");

        Map hrefMap = new HashMap();
        //记录父类id
        Map parentIdMap = new HashMap();
        //包含子集的目录
        Map isParentMap = new HashMap();
        List<ParseHtml> hrefList = new ArrayList<ParseHtml>();

        //读不到父目录的时候
        boolean bool = false;

        List Word2007List = new ArrayList();

        List<ParseHtml> titleList = DealWordByPoi.getTitle(upfileName);

        for (Element link : links) {
            if (link.toString().indexOf("_Toc") > 0) {
                int begin = link.toString().indexOf("_Toc");
                String tocId = link.toString().substring(link.toString().indexOf("_Toc"), link.toString().indexOf('"', begin + 1));
                String linkText = link.text().trim();

                Attributes classStyle = link.attributes();

                String number = linkText.split(" ")[linkText.split(" ").length - 1];

                if (link.toString().indexOf("OLE_LINK") > 0) {
                    continue;
                }
                if (!isInteger(number)) {
                    ParseHtml ph = new ParseHtml();

                    ph.setText(delNumber(linkText));
                    ph.setTocId(tocId);
                    ph.setStyle(classStyle.get("class"));

                    Word2007List.add(ph);
                    continue;
                }
                ParseHtml ph = new ParseHtml();
                ph.setText(delNumber(linkText));
                ph.setTocId(tocId);
                ph.setStyle(classStyle.get("class"));
                hrefList.add(ph);
            }
        }

        if (hrefList.size() == 0) {
            hrefList = Word2007List;
        }

        if (hrefList != null && hrefList.size() > 0) {
            if (titleList.size() >= hrefList.size()) {
                for (int i = 0; i < hrefList.size(); i++) {
                    ParseHtml ph = hrefList.get(i);
                    ParseHtml titlePh = titleList.get(i);
                    ph.setText(titlePh.getText());
                }
            }
        }
        //每一层标题的样式
        int count = 0;
        Map styleMap = new HashMap();
        Map countStyleMap = new HashMap();
        //验证和数据库里标题重复用
        Map countTitleMap = new HashMap();

        if (hrefList != null && hrefList.size() > 0) {
            for (int i = 0; i < hrefList.size(); i++) {
                ParseHtml ph = hrefList.get(i);
                if (styleMap.get(ph.getStyle()) == null) {
                    count++;
                    styleMap.put(ph.getStyle(), count);
                    countStyleMap.put(count, ph.getStyle());
                }

                if (countStyleMap.get(1) != null) {
                    if (countStyleMap.get(1).equals(ph.getStyle())) {
                        countTitleMap.put(ph.getText(), ph.getText());
                    }
                }
            }
        }

        List<Regulation> regulationList = selectAllSonDirs(catalogId, "");

        Iterator<Map.Entry<Integer, String>> entries = countTitleMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Integer, String> entry = entries.next();

            String value = entry.getValue();
            if (regulationList != null && regulationList.size() > 0) {
                for (int i = 0; i < regulationList.size(); i++) {
                    Regulation rs = regulationList.get(i);
                    String sonTitle = rs.getName();
                    if (value.equals(sonTitle)) {
                        return "标题：" + value + " 重复，请修改后上传";
                    }
                }
            }
//                    + ", Value = " + entry.getValue());
        }

        Map lastParentStyle = new HashMap();
        if (hrefList != null && hrefList.size() > 0) {
            for (int i = 0; i < hrefList.size(); i++) {
                ParseHtml ph = hrefList.get(i);

                int styleCount = 0;
                if (styleMap.get(ph.getStyle()) != null) {
                    styleCount = (int) styleMap.get(ph.getStyle());
                    String parentStyle = (String) countStyleMap.get(styleCount - 1);
                    String parentId = (String) lastParentStyle.get(parentStyle);
                    if (parentId == null) {
                        parentId = "";
                    }
                    ph.setParentId(parentId);
                }

                lastParentStyle.put(ph.getStyle(), ph.getTocId());
            }
        }

        //验证同一目录下标题是否重复
        Map mulTitleMap = new HashMap();
        if (hrefList != null && hrefList.size() > 0) {
            for (int i = 0; i < hrefList.size(); i++) {
                ParseHtml ph = hrefList.get(i);
                if (mulTitleMap.get(ph.getText()) != null) {
                    String parentId = (String) mulTitleMap.get(ph.getText());
                    if (ph.getParentId().equals(parentId)) {
                        if (!StringUtils.isEmpty(ph.getText())) {
                            return "标题：" + ph.getText() + " 重复，请修改后上传";
                        }
                    }
                }
                if (StringUtils.isEmpty(ph.getParentId())) {
                    mulTitleMap.put(ph.getText(), "");
                } else {
                    mulTitleMap.put(ph.getText(), ph.getParentId());
                }

            }
        }

        //删除重复标题
        Map delMulTitleMap = new HashMap();
        List newhrefList = new ArrayList();
        Map allTitleMap = new HashMap();
        Collections.reverse(hrefList);

        //查询本次上传的批次
        int maxBatchNo = regulationDao.selectMaxBatchNo();
        int order = 0;
        if (hrefList != null && hrefList.size() > 0) {
            for (int i = 0; i < hrefList.size(); i++) {
                order = hrefList.size() - i;
                ParseHtml ph = hrefList.get(i);
                if (delMulTitleMap.get(ph.getTocId()) == null && delMulTitleMap.get(ph.getText()) == null) {
                    delMulTitleMap.put(ph.getTocId(), ph.getTocId());
                    delMulTitleMap.put(ph.getText(), ph.getTocId());
                    ph.setBatchNo(maxBatchNo);
                    ph.setBatchOrder(order);
                    newhrefList.add(ph);
                }
                allTitleMap.put(ph.getTocId(), ph.getTocId());
            }
        }
        Collections.reverse(newhrefList);
        hrefList = newhrefList;

        //含有子集的目录
        if (hrefList != null && hrefList.size() > 0) {
            for (int i = 0; i < hrefList.size(); i++) {
                ParseHtml ph = hrefList.get(i);
                if (!StringUtils.isEmpty(ph.getParentId())) {
                    isParentMap.put(ph.getParentId(), ph.getParentId());
                }
            }
        }

        //没有子集的目录
        Map hasNoParentMap = new HashMap();
        if (hrefList != null && hrefList.size() > 0) {
            for (int i = 0; i < hrefList.size(); i++) {
                ParseHtml ph = hrefList.get(i);
                if (!StringUtils.isEmpty(ph.getParentId())) {
                    if (isParentMap.get(ph.getTocId()) == null) {
                        hasNoParentMap.put(ph.getTocId(), ph.getParentId());
                    }
                }
            }
        }

        //批量插入目錄
        if (hrefList != null && hrefList.size() > 0) {
            for (int i = 0; i < hrefList.size(); i++) {

                Regulation rl = new Regulation();
                ParseHtml ph = hrefList.get(i);

                String isParent = (String) isParentMap.get(ph.getTocId());

                if (StringUtils.isEmpty(isParent)) {
                    String parentId = (String) hasNoParentMap.get(ph.getTocId());
                    ph.setParentId((String) parentIdMap.get(parentId));
                    hrefMap.put(ph.getTocId(), ph);
                    continue;
                }
                String dbParentId = "";
                if (StringUtils.isEmpty(ph.getParentId())) {
                    dbParentId = catalogId;
                } else {
                    dbParentId = (String) parentIdMap.get(ph.getParentId());

                    if (dbParentId == null) {
                        dbParentId = catalogId;
                    }
                }

                Regulation parentInfo = regulationDao.selectRegByParentId(Integer.valueOf(dbParentId));
                String fullPath = parentInfo.getFullPath();

                if (!StringUtils.isEmpty(fullPath) && fullPath.endsWith(Const.CONST_SEPERATE)) {
                    rl.setFullPath(parentInfo.getFullPath() + dbParentId + Const.CONST_SEPERATE);
                } else {
                    rl.setFullPath(parentInfo.getFullPath() + Const.CONST_SEPERATE + dbParentId + Const.CONST_SEPERATE);
                }
//                int maxOrder = regulationDao.getMaxSorder(Integer.valueOf(dbParentId));
                rl.setUrl(parentInfo.getUrl() + Const.CONST_SEPERATE + ph.getText());
                rl.setSorder(0);
                rl.setCreateTime(new Date());
                rl.setType(Const.DIR);
                rl.setIcon(Const.ICON_DIR);
                rl.setStatus(Integer.valueOf(Const.STATUS));
                rl.setCanDel(Integer.valueOf(Const.CANDEL));
                rl.setName(ph.getText());
                rl.setLabel(ph.getText());
                rl.setParentId(Integer.valueOf(dbParentId));
                rl.setBatchNo(ph.getBatchNo());
                rl.setBatchOrder(ph.getBatchOrder());
                regulationDao.addRegulations(rl);

                parentIdMap.put(ph.getTocId(), String.valueOf(rl.getId()).trim());
                ph.setParentId(String.valueOf(rl.getId()));
                hrefMap.put(ph.getTocId(), ph);
            }
        }
        /** 处理目录信息End **/

        /** 处理文件信息start **/
        Elements divs = doc.getElementsByTag("body");
        Element div = null;
        for (Element divSel : divs) {
            Elements eleSel = divSel.getAllElements();
            if (eleSel.toString().indexOf("_Toc") > 0) {
                div = divSel;
                break;
            }
        }

        Elements elements = div.getAllElements();
//        boolean start = false;
        StringBuffer fileString = new StringBuffer();

        String lastId = "";
        //排序用
        List sorderList = new ArrayList();
        for (Element ele : elements) {
            if ("body".equals(ele.parent().parent().tagName())) {
                if (ele.toString().indexOf("_Toc") > 0) {

                    String tocId = "";
                    int a = ele.toString().indexOf("_Toc");//*第一个出现的索引位置
                    while (a != -1) {
                        tocId = ele.toString().substring(a, ele.toString().indexOf('"', a + 1));
                        if (allTitleMap.get(tocId) != null) {
                            break;
                        }

                        a = ele.toString().indexOf("_Toc", a + 1);//*从这个索引往后开始第一个出现的位置

                    }
                    if (allTitleMap.get(tocId) == null) {
                        fileString.append(ele.toString());
                        continue;
                    }

                    String linkText = ele.text().trim();
                    String str = delNumber(linkText);
                    if (allTitleMap.get(tocId) != null || delMulTitleMap.get(str) != null) {
                        if (allTitleMap.get(tocId) == null) {
                            tocId = (String) delMulTitleMap.get(str);
                        }

                        if (tocId.equals(lastId)) {

                        } else {

                            if (!StringUtils.isEmpty(lastId)) {
                                if (!StringUtils.isEmpty(fileString.toString())) {
                                    fileMap.put(lastId, fileString.toString());
                                    sorderList.add(lastId);
                                }
                            }
                            lastId = tocId;
                        }

                        fileString = new StringBuffer();
                        continue;
                    }
                } else {
                    fileString.append(ele.toString());
                }
            }
        }
        fileMap.put(lastId, fileString.toString());
        sorderList.add(lastId);

        if (hrefList != null && hrefList.size() > 0) {
            for (int x = 0; x < hrefList.size(); x++) {
                ParseHtml hrefPh = (ParseHtml) hrefList.get(x);
                String value = (String) fileMap.get(hrefPh.getTocId());
                ParseHtml ph = (ParseHtml) hrefMap.get(hrefPh.getTocId());
                // it.remove(); 删除元素
                Regulation rl = new Regulation();
                if (ph == null || StringUtils.isEmpty(value)) {
                    continue;
                }

                if (StringUtils.isEmpty(ph.getParentId())) {
                    ph.setParentId(catalogId);
                }
                rl.setParentId(Integer.valueOf(ph.getParentId()));
                rl.setLabel(ph.getText());
                rl.setCreateTime(new Date());
                rl.setType(Const.FILE);
                rl.setIcon(Const.ICON_FILE);
//                int maxOrder = regulationDao.getMaxSorder(Integer.valueOf(ph.getParentId()));
                rl.setSorder(0);

                //获取父目录信息
                Regulation parentInfo = regulationDao.selectRegByParentId(rl.getParentId());
                rl.setUrl(parentInfo.getUrl() + Const.CONST_SEPERATE + rl.getLabel());
                String fullPath = parentInfo.getFullPath();

                if (!StringUtils.isEmpty(fullPath) && fullPath.endsWith(Const.CONST_SEPERATE)) {
                    rl.setFullPath(parentInfo.getFullPath() + rl.getParentId() + Const.CONST_SEPERATE);
                } else {
                    rl.setFullPath(parentInfo.getFullPath() + Const.CONST_SEPERATE + rl.getParentId() + Const.CONST_SEPERATE);
                }
                rl.setBatchNo(ph.getBatchNo());
                rl.setBatchOrder(ph.getBatchOrder());
                regulationDao.addRegulations(rl);

                Rule rule = new Rule();
                Integer menuRuleId = rl.getId();
                rule.setRuleMenuId(rl.getParentId());
                rule.setTitle(ph.getText());
                rule.setCreateTime(new Date());
                rule.setUpdateTime(new Date());
                rule.setContent(Base64Util.encode(value));
                rule.setCatalogId(menuRuleId);
                regulationDao.saveRule(rule);

                Rule saveRule = new Rule();
                //插入新的到历史表，用来查看版本
                Session session = SecurityUtils.getSubject().getSession();
                User u = (User) session.getAttribute("userSession");
                saveRule.setOperator(u.getUsername());
                saveRule.setId(rule.getId());
                saveRule.setCreateTime(new Date());
                saveRule.setTitle(rule.getTitle());
                saveRule.setContent(rule.getContent());
                saveRuleHis(saveRule);

                Map<String, Object> esmap = new HashMap<String, Object>();
                esmap.put("title", rule.getTitle());
                esmap.put("content", DelTagsUtil.delHtmlTags(Base64Util.decode(rule.getContent())));
//                esmap.put("pageContent", Base64Util.decode(rule.getContent()));
                esmap.put("rule_menu_id", rl.getParentId());
                esmap.put("wordid", rule.getId());

                ElasticsearchUtils.addData(JSONObject.parseObject(JSONObject.toJSONString(esmap)), "rules_and_regulations", "rule", "id=" + rule.getId());

            }
        }
        return "";
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public boolean saveword(String title, String catalogId, String content) {
        List<Regulation> regulationList = selectAllSonFiles(catalogId, "");
//        if (regulationList != null && regulationList.size() > 0) {
//            for (int i = 0; i < regulationList.size(); i++) {
//                Regulation rs = regulationList.get(i);
//                String sonTitle = rs.getName();
//                if (title.equals(sonTitle)) {
//                    return false;
//                }
//            }
//        }

        Map<String, Object> map = new HashMap<>();
        Rule rule = new Rule();
        Regulation rl = new Regulation();
        rl.setParentId(Integer.valueOf(catalogId));
        rl.setLabel(title);
        rl.setCreateTime(new Date());
        rl.setType(Const.FILE);
        rl.setIcon(Const.ICON_FILE);
//        int maxOrder = getMaxSorder(rl.getParentId());
        rl.setSorder(0);
        rl.setStatus(Const.CANDEL);
        rl.setCanDel(Const.CANDEL);
        //获取父目录信息
        Regulation parentInfo = selectRegByParentId(rl.getParentId());

        String fullPath = parentInfo.getFullPath();

        if (!StringUtils.isEmpty(fullPath) && fullPath.endsWith(Const.CONST_SEPERATE)) {
            rl.setFullPath(parentInfo.getFullPath() + rl.getParentId() + Const.CONST_SEPERATE);
        } else {
            rl.setFullPath(parentInfo.getFullPath() + Const.CONST_SEPERATE + rl.getParentId() + Const.CONST_SEPERATE);
        }
        rl.setUrl(parentInfo.getUrl() + Const.CONST_SEPERATE + title);
        rl.setBatchOrder(99999);
        rl.setBatchNo(99999);
        addRegulations(rl);

        Integer menuRuleId = rl.getId();

        rule.setRuleMenuId(Integer.valueOf(catalogId));
        rule.setTitle(title);
        rule.setCreateTime(new Date());
        rule.setUpdateTime(new Date());
        rule.setContent(content);
        rule.setCatalogId(menuRuleId);
        rule.setFullPath(fullPath);
        saveRule(rule);

        Long id = rule.getId();

        Rule saveRule = new Rule();
        Session session = SecurityUtils.getSubject().getSession();
        User u = (User) session.getAttribute("userSession");
        saveRule.setOperator(u.getUsername());
        //插入新的到 历史表，用来查看版本
        saveRule.setId(id);
        saveRule.setCreateTime(new Date());
        saveRule.setTitle(rule.getTitle());
        saveRule.setContent(rule.getContent());
        saveRuleHis(saveRule);

        Map<String, Object> esmap = new HashMap<String, Object>();
        esmap.put("title", title);
        esmap.put("content", DelTagsUtil.delHtmlTags(Base64Util.decode(rule.getContent())));
//        esmap.put("pageContent", Base64Util.decode(rule.getContent()));
        esmap.put("rule_menu_id", rule.getRuleMenuId());
        esmap.put("wordid", id);

        ElasticsearchUtils.addData(JSONObject.parseObject(JSONObject.toJSONString(esmap)), "rules_and_regulations", "rule", "id=" + id);

        return true;
    }

    @Override
    public Rule selectCoverRule(String title, Integer catalogId) {
        return regulationDao.selectCoverRule(title, catalogId);
    }

    @Override
    public void saveFile(RuleFilelist rf) {
        regulationDao.saveFile(rf);

    }

    @Override
    public void updateFile(RuleFilelist rf) {
        regulationDao.updateFile(rf);

    }

    @Override
    public void delFile(RuleFilelist rf) {
        regulationDao.delFile(rf);

    }

    @Override
    public List<RuleFilelist> getFileList(String ruleId) {
        return regulationDao.getFileList(ruleId);
    }

    @Override
    public void updateAttendInfo(Rule rule) {
        regulationDao.updateAttendInfo(rule);
        //添加项目进度
        String attendUser = rule.getAttendUser();

        Map map = new HashMap();
        List<Schedule> scheduleList = regulationDao.selectSchedule(rule.getId());
        if (scheduleList != null && scheduleList.size() > 0) {
            for (int i = 0; i < scheduleList.size(); i++) {
                Schedule s = scheduleList.get(i);
                map.put(s.getAttenduser(), s);
            }
        }

        regulationDao.deleteSchedule(rule.getId());

        String[] arr = attendUser.split(",");
        for (int i = 0; i < arr.length; i++) {
            String user = arr[i];

            if (StringUtils.isEmpty(user)) {
                continue;
            }

            if (map.get(user) == null) {
                Schedule s = new Schedule();
                s.setId(CommonUtil.getUuid());
                s.setAttenduser(user);
                s.setRuleId(rule.getId());
                s.setSchedule("0%");

                regulationDao.insertUserSchedule(s);
            } else {
                Schedule s = (Schedule) map.get(user);
                regulationDao.insertUserSchedule(s);
            }
        }
    }

    @Override
    public void addCatalog(Map<String, Object> condition) {
        Regulation rl = new Regulation();
        Integer parentId = (Integer) condition.get("parentId");
        rl.setParentId(parentId);
        Regulation parentInfo = new Regulation();
        parentInfo = regulationDao.selectRegByParentId(rl.getParentId());

        String fullPath = parentInfo.getFullPath();

        if (!StringUtils.isEmpty(fullPath) && fullPath.endsWith(Const.CONST_SEPERATE)) {
            rl.setFullPath(parentInfo.getFullPath() + rl.getParentId() + Const.CONST_SEPERATE);
        } else {
            rl.setFullPath(parentInfo.getFullPath() + Const.CONST_SEPERATE + rl.getParentId() + Const.CONST_SEPERATE);
        }
//                int maxOrder = regulationDao.getMaxSorder(rl.getParentId());
        String flag = (String) condition.get("flag");
        rl.setSorder(0);

        if (!"0".equals(flag)) {
            rl.setLabel("新文件");
            saveword(rl.getLabel(), String.valueOf(parentId), "");
        } else {
            rl.setLabel("新分类");
            String url = parentInfo.getUrl() + Const.CONST_SEPERATE + rl.getLabel();
            rl.setUrl(url);
            rl.setCreateTime(new Date());
            rl.setType(Const.DIR);
            rl.setIcon(Const.ICON_DIR);
            rl.setStatus(Integer.valueOf(Const.STATUS));
            rl.setCanDel(Integer.valueOf(Const.CANDEL));
            rl.setBatchOrder(99999);
            rl.setBatchNo(99999);
            regulationDao.addRegulations(rl);
        }
//
    }

    @Override
    public void updateCatalog(Map<String, Object> condition) {
        List updateList = new ArrayList();
        Regulation rl = new Regulation();
        Integer id = (Integer) condition.get("id");
        rl.setId(id);
        String label = (String) condition.get("label");
        rl.setLabel(label);
        String url = (String) condition.get("url");
        rl.setUrl(url);
        updateList.add(rl);
        regulationDao.updateRegulationsList(updateList);
        String flag = (String) condition.get("flag");
        if (!"0".equals(flag)) {
            Rule rule = new Rule();
            rule.setTitle(label);
            rule.setUpdateTime(new Date());
            rule.setCatalogId(id);
            regulationDao.updateRuleTitle(rule);
        }

    }

    @Override
    public void deleteFile(Map<String, Object> condition) {
        Integer id = (Integer) condition.get("id");

        Rule rule = regulationDao.selectRuleByCatalogId(id);

        regulationDao.deleteRegulationMenuByid(rule.getCatalogId());
        regulationDao.deleteRule(rule.getId());

        try {
            ElasticsearchUtils.deleteDataById("rules_and_regulations", "rule", "id=" + rule.getId());
        } catch (Exception e) {

        }

    }

    private List<Regulation> selectAllSonFiles(String catalogId, String id) {

        List<Regulation> regulationList = regulationDao.selectAllSonFiles(catalogId, id);
        return regulationList;
    }


    private List<Regulation> selectAllSonDirs(String catalogId, String id) {

        List<Regulation> regulationList = regulationDao.selectAllSonDirs(catalogId, id);
        return regulationList;
    }

    /**
     * 删除序号
     *
     * @param linkText
     * @return
     */
    private String delNumber(String linkText) {
        if (linkText.toString().lastIndexOf(" ") == -1) {
            return linkText.trim();
        }
        String number = linkText.split(" ")[linkText.split(" ").length - 1];
        if (isInteger(number)) {
            int one = linkText.toString().lastIndexOf(" ");
            linkText = linkText.substring(0, one);
            return linkText.trim();
        }
        return linkText.trim();
    }

    public static boolean isInteger(String str) {
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

}
